#pragma once
#include <iostream>
#include <string>
#include <cstdio>
#include <set>
#include "Command.hpp"
#include "IntAddr.hpp"
#include "Log.hpp"

using namespace MyLog;

class Command
{
public:
    Command()
    {
        _wlist.insert("ls");
        _wlist.insert("ls -a");
        _wlist.insert("ls -al");
        _wlist.insert("pwd");
        _wlist.insert("who");
        _wlist.insert("whoami");
        _wlist.insert("ls -l");
    }

    bool IsSafeCmd(const std::string &cmd)
    {
        auto iter = _wlist.find(cmd);
        return iter != _wlist.end();
    }

    std::string Excute(const std::string &cmd,InetAddr& peer)
    {
        if(!IsSafeCmd(cmd))
        {
            return std::string("坏蛋");
        }
        std::string who = peer.GetString();

        FILE* fp = popen(cmd.c_str(),"r");
        if(nullptr == fp)
        {
            return "指令不存在: " + cmd;
        }
        std::string res;
        char line[1024];
        while(fgets(line,sizeof line,fp))
            res+=line;

        pclose(fp);

        std::string ret = who +"执行excute, result:\n" + res;
        LOG(Loglevel::INFO)<<ret;
        return ret;
    }

    ~Command(){}

private:
    std::set<std::string> _wlist;
};